<?php

    /**
     * @package      Modules
     * @subpackage   Base_Classes_Utils
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    abstract class Base_Classes_Utils_QueryBuilder
    {

    ////////////////////////////////////////////////////////////////////////////
    //                                 Methods                                //
    ////////////////////////////////////////////////////////////////////////////

        /**
         * Builds a query from simple params
         *
         * @param        string     $model
         * @param        array      $param
         * @return       Doctrine_Query
         */
        public static function build($model, array $params = array())
        {
            $query = null;

            if (!is_null($model)) {
                $query = Doctrine_Query::create()->from($model .' o');

                foreach ($params as $param => $value) {
                    switch ($param) {

                        case 'orderby':
                            $query->orderby($value);
                            break;

                        case 'leftJoin':
                            foreach ($value as $leftJoin) {
                                $query->leftJoin($leftJoin);
                            }
                            break;

                        case 'where':
                            foreach ($value as $field => $where) {
                                $_condition = array_keys($where);
                                switch ($_condition[0]) {
                                    case '=':
                                    case '!=':
                                        $values = array();
                                        $_whereValues = array_values($where);

                                        foreach ($_whereValues[0] as $val) {
                                            $values[] = (defined($val)) ? constant($val) : $val;
                                        }

                                        if ($_condition[0] == '=') {
                                            $query->whereIn($field, $values);
                                        } else {
                                            $query->whereNotIn($field, $values);
                                        }
                                        break;
                                }
                            }
                            break;
                    }
                }
            }

            return $query;
        }
    }